package com.example.orderservice.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.example.orderservice.exception.CommonException;
import com.example.orderservice.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sentinel/")
public class SentinelResourceController {

    private static final String RESOURCE = "SENTINEL-RESOURCE";

    @GetMapping("/testAspect/{id}")
    @SentinelResource(value = "testAspect",
            fallback = "fallback",
            fallbackClass = CommonException.class,
            blockHandler = "handleException",
            blockHandlerClass = CommonException.class)
    public Result testAspect(@PathVariable("id") Integer id){
        if (Integer.compare(id, Integer.parseInt("0")) == -1){
            throw new IllegalStateException("参数异常");
        }
        log.info("处理业务信息");
        return Result.ok("测试注解方式限流正常");

    }


    @PostConstruct
    private static void initFlowRule(){
        List<FlowRule> list = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource(RESOURCE);
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1);
        list.add(rule);
        FlowRuleManager.loadRules(list);
    }


}
